
// Created by carolsail 
const { ccclass, property } = cc._decorator;

import { ENUM_AUDIO_CLIP, ENUM_GAME_STATUS, ENUM_UI_TYPE } from "../Enum";
import { privacyChannel } from "../Script/privacyChannel";
import { privacyChannelOppo } from "../Script/privacyChannelOppo";
import { StaticInstance } from "../StaticInstance";
import Bottle, { TopWater } from "../game/Bottle";
import Level from "../game/Level";
import MainLayer from "../layer/MainLayer";
import AudioManager from "./AudioManager";
import DataManager, { DATA_LEVEL } from "./DataManager";
import PoolManager from "./PoolManager";
import SdkManager from "./SdkManager";
import ToastManager from "./ToastManager";

@ccclass
export default class GameManager extends cc.Component {

    stage: cc.Node = null
    levelComp: Level = null
    bottles: Bottle[] = []
    steps: { bottleFrom: number, bottleTo: number, topWater: TopWater }[] = []
    timeElapsed = 0
    onLoad() {
        StaticInstance.setGameManager(this)
        this.stage = cc.find('Stage', this.node)
    }

    onDestroy() { }

    // 开始游戏
    onGameStart() {
        DataManager.instance.reset()
        this.initGame()
    }
    update(dt: number) {
        // 累加每帧的时间
        this.timeElapsed += dt;

        // 每秒执行一次
        if (this.timeElapsed >= 1) {
            // 重置计时器
            this.timeElapsed = 0;

            // 修正存储项的获取和更新
            let onlineTimeLeft = parseInt(cc.sys.localStorage.getItem("onlineTimeLeft") || '0');
            //let onlineRewardTime = parseInt(cc.sys.localStorage.getItem("onlineRewardTime") || '0');

            // 更新剩余在线时间
            onlineTimeLeft -= 1;
            cc.sys.localStorage.setItem("onlineTimeLeft", onlineTimeLeft.toString());

            //更新界面显示
            // this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = this.formatTime(onlineTimeLeft);

            // // 检查是否可以领取奖励
            // if (onlineRewardTime <= 0) {
            //     this.onlineReward.getChildByName("time").getComponent(cc.Label).string = "领取";
            //     this.onlineReward.getComponent(cc.Button).interactable = false;
            // }
        }
    }

    // 游戏检查
    onGameCheck() {
        const bottles = this.levelComp.bottles.children
        let complete = 0
        for (let i = 0; i < bottles.length; i++) {
            const bottle = bottles[i]
            if (bottle.getChildByName('tick').active) complete += 1
        }
        if (complete >= this.levelComp.complete) {
            this.onGameOver(ENUM_UI_TYPE.WIN)
        }
        // let colors = [], some = []
        // for (let i = 0; i < bottles.length; i++) {
        //     const bottle = bottles[i]
        //     const bottleComp = bottle.getComponent(Bottle)
        //     for (let j = 0; j < bottleComp.waters.length; j++) {
        //         const waterComp = bottleComp.waters[j]
        //         const color = waterComp.info.color
        //         if (colors.indexOf(color) == -1) colors.push(color)
        //     }
        //     if (!bottleComp.isEmptyBottle()) {
        //         some.push(bottleComp.checkSomeWater())
        //     }
        // }
        // if (colors.length == some.length && some.findIndex(bool => bool == false) == -1) {
        //     const temp = Array.from(new Set(some))
        //     if (temp.length <= 1) {
        //         this.onGameOver(ENUM_UI_TYPE.WIN)
        //     }
        // }
    }

    // 游戏结束
    onGameOver(ui: ENUM_UI_TYPE) {
        DataManager.instance.status = ENUM_GAME_STATUS.UNRUNING
        if (DataManager.instance.stageModel) {
            //挑战模式没有关卡

        } else {
            DataManager.instance.level += 1
        }
        if (DataManager.instance.level > DataManager.instance.levelMax) {
            DataManager.instance.levelMax = DataManager.instance.level
            // 加入排行榜
            SdkManager.instance.setRank(DataManager.instance.levelMax)
        }
        DataManager.instance.save()
        this.scheduleOnce(() => {
            StaticInstance.uiManager.toggle(ui)
        }, 0.8)
    }

    // 重置
    onGameReset() {
        DataManager.instance.skillReset = true
        this.onGameStart()
    }

    // 回退一步
    onGameUndo() {
        const step = this.steps.pop()
        this.steps.push(step)
        if (step) {
            const bottles = this.levelComp.bottles.children
            const bottleFrom = bottles.find(bottle => bottle.getComponent(Bottle).bottleIndex == step.bottleFrom)
            const bottleTo = bottles.find(bottle => bottle.getComponent(Bottle).bottleIndex == step.bottleTo)
            if (bottleFrom.getComponent(Bottle).checkState() && bottleTo.getComponent(Bottle).checkState()) {
                console.error("============", "倒回去1", bottleFrom.getComponent(Bottle), step.topWater)
                if (DataManager.instance.tool > 0) {
                    console.error("============", "倒回去2", bottleFrom.getComponent(Bottle), step.topWater)
                    bottleTo.getComponent(Bottle).pourWater(bottleFrom.getComponent(Bottle), step.topWater)

                    DataManager.instance.tool -= 1
                    DataManager.instance.save()
                    this.node.parent.getChildByName("UI").getChildByName("MainLayer").getComponent(MainLayer).freshTool()

                } else {
                    console.error("============", "倒回去3", bottleFrom.getComponent(Bottle), step.topWater)

                    switch (privacyChannel.channel) {
                        case "oppo":
                        case "oppo1":
                            (privacyChannel.getChannel() as privacyChannelOppo).showVideo(() => {
                                bottleTo.getComponent(Bottle).pourWater(bottleFrom.getComponent(Bottle), step.topWater)
                                this.steps.pop()
                            })
                            break
                        default:
                            privacyChannel.getChannel().showVideo(() => {
                                bottleTo.getComponent(Bottle).pourWater(bottleFrom.getComponent(Bottle), step.topWater)
                                this.steps.pop()
                            })
                            break
                    }
                }
            } else {
                ToastManager.instance.show('操作太快了~', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })

            }
        } else {
            ToastManager.instance.show('不需要回退了~', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }

    // 初始化游戏
    async initGame() {
        DataManager.instance.status = ENUM_GAME_STATUS.UNRUNING
        this.bottles = []
        this.steps = []
        this.stage.removeAllChildren()
        const level = PoolManager.instance.getNode('Level', this.stage)
        this.levelComp = level.getComponent(Level)
        this.levelComp.init()
        StaticInstance.uiManager.setMainCurrenLevel()
        DataManager.instance.status = ENUM_GAME_STATUS.RUNING
        await StaticInstance.fadeManager.fadeOut()
    }
}
